var express = require('express')
var router = express.Router();
var multer = require('multer')
var fs = require('fs')
var path = require('path')
var mineType = require("mime-types")

const { get, set } = require('../db/redis')


// 磁盘存储
var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, 'uploads/')
  },
  filename: function (req, file, cb) {
    cb(null,  Date.now() + '-' + file.originalname )
  }
})

var upload = multer({ storage: storage })

router.post('/', upload.single('file'), function (req,res) {
  console.log('req.body', req.body)
  console.log('req.file', req.file)
  console.log('req.files', req.files)

  set('filename', req.file.filename)

  res.send('请求成功')
})

router.get('/file', function (req,res) {

  get('filename').then(filename => {
    if (filename) {
      let dir =  path.resolve(__dirname, '../uploads/', filename)
      fs.readFile(dir, function (err, data) {
        if (err) {
          console.log(' 文件读取失败');
        } else {
          let bufferData = Buffer.from(data).toString('base64')
          let base64 = "data:" + mineType.lookup(dir) + ';base64,' + bufferData
          res.send(base64)
        }
      })
    } else {
      res.send('文件暂未上传')
    }
  })
})

module.exports = router;
